import {defineStore} from "pinia";
export const messageStore = defineStore('messageStore', () => {
    const hasNew: Ref<boolean> = ref(false)
    // const userMap:Map<string, PreviewItemOfMessage> = new Map<string, PreviewItemOfMessage>()
    const userMap =ref (new Map<string, PreviewItemOfMessage>())

    function addMsg(rawMsg: string) {
        hasNew.value = true
        const tmp = JSON.parse(rawMsg) as any
        userMap.value.set(tmp.senderUseralias, {
            message: tmp.message,
            isRead: false,
            receiveId: tmp.senderId,
            sender: tmp.senderUseralias
        })
    }
    function removeMsg(userAlias:string) {
        userMap.value.delete(userAlias)
    }
    return {hasNew,userMap,addMsg,removeMsg}
}, {
    persist: {
        storage: piniaPluginPersistedstate.localStorage(),
        //自定义序列化和反序列化方法
        serializer:{
            serialize:(state)=>{
                //将Map转换为数组进行存储

                const userMapArray=Array.from(state.userMap.entries());
                // const userMapArray='asdasd';
                // try {
                //     console.log(JSON.stringify(
                //         {
                //             ...state,
                //             userMap:Array.from(state.userMap.entries())
                //         }
                //     ))
                // }catch (error){console.log(error)}
                return JSON.stringify({
                    ...state,
                    userMap:userMapArray
                });
            },
            deserialize:(saveState)=>{
                const parsedState=JSON.parse(saveState)
                //将数组转换回Map
                parsedState.userMap=new Map(parsedState.userMap);
                return parsedState
            }
        }

    }
})